﻿Imports Microsoft.VisualBasic
Imports log4net

Public Class FctrGenClass
    Private Shared logger As log4net.ILog = LogManager.GetLogger("FctrGenClass")

    Shared Sub GenFctrView(ByVal users As String, ByVal planyear As Integer)
        Dim arrlist As New ArrayList
        Dim user_name As String = users
        Dim usadap As New fctrDSTableAdapters.UserFundCentersTableAdapter
        Dim usdt As New fctrDS.UserFundCentersDataTable
        'usdt = usadap.GetDataByUserName(user_name)
        usdt = usadap.GetDataByUserName1(user_name, planyear) 'Add by Orn 11/08/2558

        Dim adap As New fctrDSTableAdapters.fctr_viewTableAdapter
        Dim newtime As Integer = 10000
        Try
            newtime = Val(ConfigurationManager.AppSettings("QueryTimeOut"))
            adap.SetCommandTimeOut(newtime)
        Catch ex As Exception
        End Try

        adap.DeleteByUserName(user_name, planyear)

        Dim fcadap As New fctrDSTableAdapters.FundCenterHierarchiesTableAdapter
        Dim fctradap As New fctrDSTableAdapters.FundCentersTableAdapter
        Dim fctrdt As New fctrDS.FundCentersDataTable
        Dim sql As String = ""
        Dim i = 0

        For Each item As fctrDS.UserFundCentersRow In usdt
            If i > 0 Then
                sql += " UNION "
            End If
            sql += " SELECT *, " & item.Id & " AS UserFundCenterId  FROM FundCenters WHERE (Fundcentercode between "
            sql += "'" & item.FromFundCenter_FundCenterCode & "' and '" & item.ToFundCenter_FundCenterCode & "')"
            sql += " AND PlanYear = " & planyear

            i += 1
        Next
        fctradap.GetDataByFilter(fctrdt, sql)
        If fctrdt.Count <> 0 Then
            For Each item2 As fctrDS.FundCentersRow In fctrdt
                Dim parent As String = ""
                Try
                    parent = fcadap.GetParentCode(item2.FundCenterCode)
                Catch ex As Exception
                    parent = "0"
                End Try
                Dim chk As Integer
                chk = adap.CheckExist(item2.FundCenterCode, user_name, planyear)
                If chk = 0 Then
                    adap.Insert(item2.UserFundCenterId, item2.FundCenterCode, user_name, parent, planyear)
                    logger.Info("insert data to fund center view with values " & item2.UserFundCenterId & ":" & item2.FundCenterCode & ":" & user_name & ":" & planyear)
                End If
            Next
        End If

        adap.UpdateParent0(user_name)
    End Sub

End Class

